const express = require("express");
const mongoose = require("mongoose");

const Shop = require("../../models/Shop");

const router = express.Router({
  mergeParams: true,
});

const _model = Shop;

// 创建店铺
router.post("/", async (req, res) => {
  const model = await _model.create(req.body);
  res.send(model);
});

//查询个人名下店铺
router.get("/user/:userId", async (req, res) => {
  const queryOptions = {
    userId: mongoose.Types.ObjectId(req.params.userId),
  };
  // const items = await _model.find().setOptions(queryOptions);
  const items = await _model.aggregate([
    {
      $match: queryOptions,
    },
    {
      $lookup: {
        from: "users",
        localField: "userId",
        foreignField: "_id",
        as: "user",
      },
    },
    {
      $lookup: {
        from: "cars",
        localField: "_id",
        foreignField: "shopId",
        as: "cars",
      },
    },
  ]);
  res.send(items);
});

// 查询店铺
router.get("/:id", async (req, res) => {
  const items = await _model.aggregate([
    {
      $match: {
        _id: mongoose.Types.ObjectId(req.params.id),
      },
    },
    {
      $lookup: {
        from: "users",
        localField: "userId",
        foreignField: "_id",
        as: "user",
      },
    },
    {
      $lookup: {
        from: "cars",
        localField: "_id",
        foreignField: "shopId",
        as: "cars",
      },
    },
  ]);
  res.send(items);
});

router.put("/:id", async (req, res) => {
  const model = await _model.findByIdAndUpdate(req.params.id, req.body);
  res.send(model);
});

router.delete("/:id", async (req, res) => {
  await _model.findByIdAndDelete(req.params.id, req.body);
  res.send({
    success: true,
  });
});

router.get("/", async (req, res) => {
  const queryOptions = {};
  const items = await _model.find().setOptions(queryOptions);
  res.send(items);
});

module.exports = router;
